/*
 * game.cc
 * This file is part of Quarto
 *
 * Copyright (C) 2012 - Ian Liu Rodrigues <ian.liu88@gmail.com>
 *
 * Quarto is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Quarto is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Quarto. If not, see <http://www.gnu.org/licenses/>.
 */

#include "game.hpp"

using namespace br_unicamp;

Game::Game(Player* player1,
           Player* player2,
           GameFactory* factory)
{
  this->player1 = player1;
  this->player2 = player2;
  this->factory = factory;
  this->pieces = factory->getAllPieces();
}

void Game::run(void) {
  Player* p1;
  Player* p2;
  const Piece* piece;
  int place;

  choosePlayersOrder(&p1, &p2);
  Board *board = factory->getEmptyBoard();

  while (!board->gameEnded()) {
    board->showBoard();
    onPieceRequest(*p1, *pieces);
    piece = p1->askPiece(*pieces, *board);
    onPlaceRequest(*p2, *board, *pieces);
    place = p2->askPlace(*pieces, *board, *piece);
    board->markPlace(place, *piece);
    pieces->remove(*piece);
    swapOrder(&p1, &p2);
    board->showBoard();
  }

  if (board->gameDraw()) {
    onGameFinish(0);
  } else {
    onGameFinish(p1);
  }
}

void Game::choosePlayersOrder(Player**p1, Player**p2) const
{
  *p1 = player1;
  *p2 = player2;
}

void Game::swapOrder(Player** p1, Player** p2) const
{
  Player *aux = *p1;
  *p1 = *p2;
  *p2 = aux;
}
